// pages/cart/index/index.js
const Controllers = require('../../controllers/Controller.js').controller;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    globalStype:'',
    isSelectAll: false,
    total: 0,
    sum: 0,
    tabbar: [],
    shopId: '',
    cartList: [],
    invalidList: [],
    isReturn:false,
    tabBottom:132
  },
  //获取手机型号改变操作栏
  getPhoneInfo(){
    let _self = this
    wx.getSystemInfo({
      success: function(res) {
       let model = res.model;
       if (model.search('iPhone X') != -1 || model.search('iPhone 11') != -1 || model.search('iPhone 12') != -1) {
         console.log("是大屏手机")
        _self.setData({
          tabBottom:200
        })
       }
      }
     })
  },
  //导航切换
  tabChange(e) {
    var index = e.detail.index;
    if (index == 1) {
      wx.requestSubscribeMessage({
        tmplIds:['CgSkX1UN123rlfAQ9zXiMyfiF1ugDkOsd8yLmvcbHt0','IoewIlKNaUfOLOhKUOdPKMOnJxdtdqWGfOotuOB2R70','TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'],//'TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'
        success:res=>{
          console.log(res)
        },
        complete:()=>{
          wx.reLaunch({
            url: "/pages/Mall/Mall"
          });
        }
      })
    }
    if (index == 0) {
     // wx.reLaunch({
      //   url: "/pages/Index/Index"
      // });

      wx.requestSubscribeMessage({
        tmplIds:['CgSkX1UN123rlfAQ9zXiMyfiF1ugDkOsd8yLmvcbHt0','IoewIlKNaUfOLOhKUOdPKMOnJxdtdqWGfOotuOB2R70','TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'],//'TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'
        success:res=>{
          console.log(res)
        },
        complete:()=>{
          wx.reLaunch({
            url: "/pages/Index/Index"
          });
        }
      })
    }
    if (index == 3) {
      wx.reLaunch({
        url: "/pages/my/my-index/my-index"
      });
    }
  },
  //获取购物车列表
  getCartList(isRefresh = false) {
    //获取数据
    Controllers.cartList({ shopId: this.data.shopId }).then(res => {
      console.log("res", res)
      let invalidList = res.data.invalid
      let cartList = res.data.normal
      let sum = 0
      let total = 0
      cartList.forEach(item => {
        item.select = false
      })
      if (isRefresh) {
        cartList.forEach(item => {
          var price=0;
          if((this.data.myInformationdata.vip==1 || this.data.myInformationdata.vip==2) && item.vipPrice && item.vipPrice>=0){
            price=item.vipPrice;
          }else{
            price=item.price;
          }

          if (item.select) {
            sum += item.num
            total += item.num * price
          }
          this.setData({
            sum,
            total
          })
        })
      }
      this.setData({
        invalidList,
        cartList,
      })
    })
  },
  //跳转详情
  goDetail(e) {
    let url = e.currentTarget.dataset['url'];
    wx.navigateTo({
      url: url
    })
  },
  //跳转提交订单
  goPage() {
    let list
    list = this.data.cartList.filter(item => item.select)
    if (list.length > 0) {
      list = JSON.stringify(list)
      wx.navigateTo({
        url: '/pages/cart/submitOrder/submitOrder?list=' + list,
      })
    } else {
      wx.showToast({
        title: "请选择商品",
        icon: 'none',
        duration: 800
      });
    }
  },
  //删除商品
  deleteCart(e) {
    let index = e.currentTarget.dataset['index'];
    let ids
    if (index == "all") {
      ids = []
      this.data.cartList.forEach(item => {
        if (item.select) {
          ids.push(item.id)
        }
      })
      ids = ids.join(",")
    } else {
      ids = this.data.cartList[index].id
    }
    Controllers.delGoods({ shopId: this.data.shopId, cartIds: ids }).then(res => {
      if (res.code == 1) {
        this.getCartList(true)
        wx.showToast({
          title: "删除成功",
          icon: 'none',
          duration: 800
        });
      }
    })
  },
  //选择商品
  selectGood(e) {
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let isSelectAll
    let sum = 0
    let total = 0
    cartList[index].select = !cartList[index].select;
    cartList.forEach(item => {
      var price=0;
      if((this.data.myInformationdata.vip==1 || this.data.myInformationdata.vip==2) && item.vipPrice && item.vipPrice>=0){
        price=item.vipPrice;
      }else{
        price=item.price;
      }
      if (item.select) {
        sum += item.num
        total += item.num * price
      }
    })
    for (let i = 0; i < cartList.length; i++) {
      if (!cartList[i].select) {
        console.log("不全选")
        isSelectAll = false
        break
      } else {
        console.log("全选")
        isSelectAll = true
      }
    }
    this.setData({
      cartList,
      isSelectAll,
      sum,
      total
    })
    console.log(this.data.isSelectAll)
  },
  //加减商品数量
  addSubtract(e) {
    let type = e.currentTarget.dataset['type'];
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let sum = 0
    let total = 0
    if (type == "add") {
      cartList[index].num += 1
    } else if (cartList[index].num > 1) {
      cartList[index].num -= 1
    }
    cartList.forEach(item => {
      var price=0;
      if((this.data.myInformationdata.vip==1 || this.data.myInformationdata.vip==2) && item.vipPrice && item.vipPrice>=0){
        price=item.vipPrice;
      }else{
        price=item.price;
      }
      if (item.select) {
        sum += item.num
        total += item.num * price
      }
    })
    Controllers.updateCart({ shopId: this.data.shopId, cartId: cartList[index].id, num: cartList[index].num }).then(res => {
      if (res.code == 1) {
        this.setData({
          cartList: cartList,
          sum,
          total
        })
      }
    })
  },
  //加减失效商品数量
  addInvalidListSubtract(e) {
    let type = e.currentTarget.dataset['type'];
    let index = e.currentTarget.dataset['index'];
    let invalidList = this.data.invalidList;
    if (type == "add") {
      invalidList[index].num += 1
    } else if (invalidList[index].num > 1) {
      invalidList[index].num -= 1
    }
    Controllers.updateCart({ shopId: this.data.shopId, cartId: invalidList[index].id, num: invalidList[index].num }).then(res => {
      if (res.code == 1) {
        this.setData({
          invalidList: invalidList
        })
      }
    })
  },
  //全选
  selectAll() {
    let isSelectAll = this.data.isSelectAll
    isSelectAll = !isSelectAll
    let cartList = this.data.cartList;
    let sum = 0
    let total = 0
    cartList.forEach(item => {
      var price=0;
      if((this.data.myInformationdata.vip==1 || this.data.myInformationdata.vip==2) && item.vipPrice && item.vipPrice>=0){
        price=item.vipPrice;
      }else{
        price=item.price;
      }
      if (isSelectAll) {
        item.select = true
      } else {
        item.select = false
      }

      if (item.select) {
        sum += item.num
        total += item.num * price
      }
    })
    this.setData({
      cartList,
      isSelectAll,
      sum,
      total
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({globalStype:app.globalData.globalStype})
    this.getPhoneInfo()
    if (app.globalData.shopId) {
      this.setData({
        shopId: app.globalData.shopId
      })
    }
    let isReturn = false
    if(options.isReturn == 1){
      isReturn = true
    }
    console.log("isReturn",isReturn)
    this.setData({
      isReturn,
      tabbar: this.data.globalStype=='pinStyle'?app.globalData.tabbar:app.globalData.tabbar2,
    })
    
  },

  myInformation(){
    //获取数据
    Controllers.myInformation({shopId:this.data.shopId}).then(res => {
      this.setData({
        myInformationdata:res.data.accountRelation
      })
      this.getCartList()
    }).catch(res=>{
      this.getCartList()
    })
  },
  onShow(){
    this.myInformation()
  },
  changenums(e){
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let sum = 0
    let total = 0
    cartList[index].num = Number(e.detail.value)
    cartList.forEach(item => {
      var price=0;
      if((this.data.myInformationdata.vip==1 || this.data.myInformationdata.vip==2) && item.vipPrice && item.vipPrice>=0){
        price=item.vipPrice;
      }else{
        price=item.price;
      }
      if (item.select) {
        sum += item.num
        total += item.num * price
      }
    })
    Controllers.updateCart({ shopId: this.data.shopId, cartId: cartList[index].id, num: cartList[index].num }).then(res => {
      if (res.code == 1) {
        this.setData({
          cartList: cartList,
          sum,
          total
        })
      }
    })
  },
})